from rest_framework import status,viewsets
from sys_manager.models import PermissionsModel,RolesModel
from rest_framework.decorators import action
from rest_framework.response import Response
from ERP_system.apps.sys_manager.serializer_kit.roles_serializer import PermissionSerializer

from ERP_system.utils.multiple_destory import MultipleDestoryMixin
import logging

class  PermissionView(viewsets.ModelViewSet,MultipleDestoryMixin):


    queryset = PermissionsModel.objects.all()
    serializer_class = PermissionSerializer

    @action(methods=['get'], detail=False)
    def find_permissions_by_menu(self,request,*args,**kwargs):
        menu_id=request.query_params.get('menu_id')
        permission_list=PermissionsModel.objects.filter(menu__id=menu_id).all()
        #序列化
        ser = PermissionSerializer(instance=permission_list, many=True)
        return Response(ser.data)

    @action(methods=['delete'], detail=False)
    def multiple_delete(self, request, *args,**kwargs):
        delete_ids = request.data.get('ids')

        if delete_ids:
            PermissionsModel.objects.filter(id__in=delete_ids).delete()
            return Response(data={'message': '删除成功'}, status=status.HTTP_200_OK)
        else:
            return Response(data={'detail': 'ids参数非法'}, status=status.HTTP_400_BAD_REQUEST)

    @action(methods=['get'], detail=False)
    def find_permissions(self, request, *args, **kwargs):#返回当前角色所有的已拥有的权限id列表 以及ERP系统中所有的权限（树形）结构
        result={}  #返回的整个字典数据
        rid = request.query_params.get('rid',None)
        if rid:
            ids=RolesModel.objects.filter(id=rid).values_list('permissions',flat=True).distinct()

            result['ids']=ids


        permission_dicts=PermissionsModel.objects.values('id','name','menu__name','menu__id','menu__parent_id')
        tree_dict={}
        tree_list=[]
        for items in permission_dicts:
            tree_dict[items['menu__id']]=items

        for i in tree_dict:
            # 子菜单
            print(tree_dict[i])
            if tree_dict[i]['menu__parent__id']:

                pid=tree_dict[i]['menu__parent__id']
                parent=tree_dict[pid]
                child=dict()
                child['menu__id']=tree_dict[i]['menu__id']
                child['menu__name']=tree_dict[i]['menu__name']
                child.setdefault('permissions',[])
                parent.setdefault('children', []).append(child)

            # 父菜单
            else:
                tree_list.append(tree_dict[i])

        for parent in tree_list:
            if 'children' in parent:
                for child in parent['children']:
                    for node in permission_dicts:
                        if node['menu_parent__id'] and node['menu__id']==child['menu__id']:
                            child['permissions'].append(node)



        return Response(data=tree_dict)




